/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.navid.trafalgar.mod.counterclock.statelisteners;

import com.jme3.renderer.ViewPort;
import com.navid.trafalgar.manager.states.PrestartState;
import com.navid.trafalgar.manager.states.StartedState;
import com.navid.trafalgar.manager.GameConfiguration;
import com.navid.trafalgar.manager.GameStatus;
import com.navid.trafalgar.model.AShipModel;
import com.navid.trafalgar.persistence.CandidateRecord;
import com.navid.trafalgar.persistence.RecordPersistenceService;
import com.navid.trafalgar.persistence.RecordPersistenceServiceFactory;
import com.navid.trafalgar.persistence.StepRecord;

/**
 *
 * @author anf
 */
public class GhostViewer implements PrestartState, StartedState {

    AShipModel ghost;
    CandidateRecord ghostRecord;
    ViewPort rootVP;
    boolean ghostAvailable;
    int ghostIndex = 0;
    RecordPersistenceService persistenceService = RecordPersistenceServiceFactory.getFactory(RecordPersistenceServiceFactory.Type.LOCAL);
    GameStatus gameStatus;
    GameConfiguration gameConfiguration;

    public GhostViewer(GameStatus gameStatus, GameConfiguration gameConfiguration) {
        this.gameStatus = gameStatus;
        this.gameConfiguration = gameConfiguration;
    }
    
     public void onPrestart(float tpf) {
        this.rootVP = gameStatus.getViewPort();


        if (gameConfiguration.isShowGhost()) {
            ghost = gameConfiguration.getModelBuilder().buildGhost(gameStatus.getGameDefinition());
            ghostRecord = persistenceService.getGhost(1, gameConfiguration.getMap());
        }

        if (ghost != null && ghostRecord != null && ghostRecord.getStepRecord() != null) {
            ghostAvailable = true;
            gameStatus.getGameNode().attachChild(ghost);
            rootVP.attachScene(ghost);
        }
    }

    public void onStarted(float tpf) {
        if (ghostAvailable) {
            for (; ghostIndex < ghostRecord.getStepRecord().size();) {
                StepRecord currentStepRecord = (StepRecord) ghostRecord.getStepRecord().get(ghostIndex);
                if (currentStepRecord.getTimestamp() < gameStatus.getTime()) {
                    ghost.updateFromRecord(currentStepRecord);
                    ghostIndex++;
                } else {
                    break;
                }
            }
        }
    }

    public void onUnload() {
        rootVP.detachScene(ghost);
    }

   
}
